package xiao.trip.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import xiao.trip.dao.user1;


@Controller
public class UserController {
    @Autowired
    user1 userDAO;

    @RequestMapping("/loginCheck")
    public String loginCheck(HttpServletRequest request, Map<String, String> map) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        if (username == null && password == null) {
            map.put("error", "您还未登录");
            return "user/login";
        } else if (userDAO.login(username, password).size() == 0) {
            map.put("error", "用户名或密码错误");
            System.out.println("用户密码错误");
            return "user/login";
        } else {
            map.put("error", "您已成功登录");
            session.setAttribute("username", username);
            System.out.println("用户会话域存储的数据是" + session.getAttribute("username"));
            System.out.println(username);
            return "user/login";
        }


    }

    @RequestMapping("/homepage")
    public String homepage(HttpSession session, Model model) {
        model.addAttribute("username", session.getAttribute("username"));
        return "user/index";
    }

    @RequestMapping("/register")
    public String register(HttpServletRequest request, Map map) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username == null && password == null) {
            map.put("error", "您还未注册");
        } else if (userDAO.login(username, password).size() == 0) {
            userDAO.register(username, password);
            map.put("error", "用户注册成功");
        } else {
            map.put("error", "用户已注册可直接登录");
        }
        return "user/register";
    }
}



